#!/usr/bin/env python
PKG = 'nfc_reader' # this package name
import roslib; roslib.load_manifest(PKG)

import rospy
from std_msgs.msg import *
from nfc_reader.msg import *
import serial

ser=serial.Serial('/dev/ttyACM0')

def getData():
    return ord(ser.read())

def main():
    pub = rospy.Publisher('ndef', Ndef)
    rospy.init_node('nfc_reader', anonymous=True)
    #try:
    while ser.isOpen():
            b=getData()
            while b==0: b=getData()
	    if(b==0xff):
		msg=Ndef()
	        size=getData()
                print "Size :",size*8
	        csize=getData()
	        if ((size+csize)&0xff)==0:
	            data=ser.read(size*8)
	            if(getData()==0) : 
	   	        print 'data:', data[3:len(data)]
			msg.text.data=data[3:len(data)]
			msg.header=Header()
			msg.header.stamp=rospy.Time.now()
       		        pub.publish(msg)
		    else :print 'ERROR'
	        else: print 'ERROR'
    #except:   
    #    ser.close()
if __name__ == '__main__':
    main()
